package com.shouer.doc.ui.conversation.presenter;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.shouer.doc.BuildConfig;
import com.shouer.doc.application.response.QueryUserResponse;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.dialog.ShouerLoadingDialogUtil;
import com.shouer.doc.event.CloseOrdEvent;
import com.shouer.doc.event.LoginToRongEvent;
import com.shouer.doc.event.RollBackOrdEvent;
import com.shouer.doc.request.GsonRequest;
import com.shouer.doc.request.RequestUtil;
import com.shouer.doc.ui.conversation.response.CloseOrderResponse;
import com.shouer.doc.ui.conversation.response.PayControllerDocResponse;
import com.shouer.doc.ui.conversation.response.QueryCovOrderResponse;
import com.shouer.doc.ui.conversation.response.QueryLeftTimeResponse;
import com.shouer.doc.ui.conversation.response.RollBackResponse;
import com.shouer.doc.ui.conversation.view.ICoversionView;
import com.shouer.doc.ui.login.LoginActivity;
import com.shouer.doc.ui.login.presenter.ILoginPresenter;
import com.shouer.doc.ui.login.response.GetTokenResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

/**
 * Created by ZXL on 2016/12/6.
 */

public class ConversionPresenterCompl implements IConversationPresenter {


    private ICoversionView coversionView;
    private Request queryLeftTimeRequest;
    private boolean isFirstLoginToRong = true;


    public ConversionPresenterCompl(ICoversionView coversionView) {
        this.coversionView = coversionView;
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDeatroy() {
        EventBus.getDefault().unregister(this);
        this.coversionView = null;
    }

    @Override
    public void closeOrder(String patId, final String orderId) {

        Map<String, String> param = new HashMap<>();
        param.put("orderId", orderId);
        param.put("patId", patId);
        param.put("docId", coversionView.getApp().getUserDocInfo().getDocId());
        param.put("type", "2");

        final GsonRequest<CloseOrderResponse> request = new GsonRequest("receiveOrder", CloseOrderResponse.class, new Response.Listener<CloseOrderResponse>() {
            @Override
            public void onResponse(CloseOrderResponse response) {
                response.setOrderId(orderId);
                EventBus.getDefault().post(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                coversionView.closeOrderFailed("网络异常 关闭订单失败");
            }
        });

        RequestUtil.sendRequest(coversionView.getContext(), param, request);
    }

    @Override
    public void queryOrderInfo(String orderId) {

        if (BuildConfig.DEBUG) {
            Log.i(IConversationPresenter.class.getSimpleName(), "进入会话页面没有带入订单信息，根据订单号查询订单信息 订单号:" + orderId);
        }
        Map<String, String> param = new HashMap<>();
        param.put("orderId", orderId);
        final GsonRequest<QueryCovOrderResponse> request = new GsonRequest("queryOrder", QueryCovOrderResponse.class, new Response.Listener<QueryCovOrderResponse>() {
            @Override
            public void onResponse(QueryCovOrderResponse response) {
                EventBus.getDefault().post(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                coversionView.queryOrderFailed("网络异常 查询订单信息失败");
            }
        });

        RequestUtil.sendRequest(coversionView.getContext(), param, request);

    }

    @Override
    public void queryOrderLeftTime(String orderId) {

        ShouerLoadingDialogUtil.getInstance().show(coversionView.getContext());
        if (null != queryLeftTimeRequest && !queryLeftTimeRequest.isCanceled()) {
            return;
        }
        ShouerLoadingDialogUtil.getInstance().show(coversionView.getContext());
        Map<String, String> param = new HashMap<>();
        param.put("orderId", orderId);

        final GsonRequest<QueryLeftTimeResponse> request = new GsonRequest("queryLeftTime", QueryLeftTimeResponse.class, new Response.Listener<QueryLeftTimeResponse>() {
            @Override
            public void onResponse(QueryLeftTimeResponse response) {
                EventBus.getDefault().post(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                coversionView.queryLeftTimeFailed("网络异常 查询剩余时间失败");
            }
        });

        queryLeftTimeRequest = RequestUtil.sendRequest(coversionView.getContext(), param, request);
    }

    @Override
    public void queryUserInfo() {

        Map<String, String> param = new HashMap<>();
        param.put("userId", coversionView.getUserId());

        final GsonRequest<QueryUserResponse> request = new GsonRequest(ShouerConst.APP_SERVER_https, "queryUser", QueryUserResponse.class, new Response.Listener<QueryUserResponse>() {
            @Override
            public void onResponse(QueryUserResponse response) {
                EventBus.getDefault().post(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                coversionView.queryUserFailed("网络异常 查询用户信息失败");
            }
        });
        RequestUtil.sendRequest(coversionView.getContext(), param, request);


    }

    @Override
    public void payControllerDoc(String orderId, String type, final String cardType, String userId, String docId, String times) {
        Map<String, String> param = new HashMap<>();
        param.put("orderId", orderId);
        param.put("type", type);
        param.put("cardType", cardType);
        param.put("userId", userId);
        param.put("docId", docId);
        param.put("times", times);


        final GsonRequest<PayControllerDocResponse> request = new GsonRequest(ShouerConst.APP_SERVER_https, "payControllerDoc", PayControllerDocResponse.class, new Response.Listener<PayControllerDocResponse>() {
            @Override
            public void onResponse(PayControllerDocResponse response) {
                response.setCardType(cardType);
                EventBus.getDefault().post(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                coversionView.payControllerDocFailed("网络异常 健康卡扣卡失败");
            }
        });
        RequestUtil.sendRequest(coversionView.getContext(), param, request);
    }

    @Override
    public void reConnect(String appToken) {
        RongIM.connect(appToken, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Log.d(ConversionPresenterCompl.class.getSimpleName(), "onTokenIncorrect()");
                EventBus.getDefault().post(new LoginToRongEvent(false));
            }

            @Override
            public void onSuccess(String s) {
                Log.d(ConversionPresenterCompl.class.getSimpleName(), "onSuccess:" + s);
                EventBus.getDefault().post(new LoginToRongEvent(true));
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

                Log.d(ConversionPresenterCompl.class.getSimpleName(), "--onError" + errorCode);
                if (errorCode != RongIMClient.ErrorCode.RC_CONN_OVERFREQUENCY) {
                    EventBus.getDefault().post(new LoginToRongEvent(false));
                } else {
                    EventBus.getDefault().post(new LoginToRongEvent(true));
                }
            }
        });
    }

    /**
     * 订单回退
     * */
    @Override
    public void rollBackOrder(final String orderId) {

        ShouerLoadingDialogUtil.getInstance().show(coversionView.getContext());

        Map<String, String> param = new HashMap<>();
        param.put("orderId", orderId);
        param.put("docId", coversionView.getApp().getUserDocInfo().getDocId());
        param.put("type", "3");

        final GsonRequest<RollBackResponse> request = new GsonRequest("receiveOrder", RollBackResponse.class, new Response.Listener<RollBackResponse>() {
            @Override
            public void onResponse(RollBackResponse response) {
                response.setOrderId(orderId);
                EventBus.getDefault().post(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                coversionView.rollBackOrderFailed("网络异常 订单回退失败");
            }
        });

        RequestUtil.sendRequest(coversionView.getContext(), param, request);


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginToRongEvent event) {
        if (BuildConfig.LOG_DEBUG) {
            Log.e(ConversionPresenterCompl.class.getSimpleName(), "LoginToRongEvent");
        }
        if (event.isSuccess()) {

            Log.i(IConversationPresenter.class.getSimpleName(),"重连接成功！！！！！！");

        } else {
            if (!isFirstLoginToRong) {
                Intent intent=new Intent(coversionView.getContext(), LoginActivity.class);
                coversionView.getContext().startActivity(intent);
                coversionView.close();
            } else {
                isFirstLoginToRong = false;
                getRongIMToken(coversionView.getApp().getUserDocId());
            }
        }
    }

    private void getRongIMToken(String userId) {
        Log.i(ConversionPresenterCompl.class.getSimpleName(),"getRongIMToken");
        Map<String, String> param = new HashMap<>();
        param.put("userId", userId);

        final GsonRequest<GetTokenResponse> request = new GsonRequest(ShouerConst.APP_SERVER_https,"getToken", GetTokenResponse.class, new Response.Listener<GetTokenResponse>() {
            @Override
            public void onResponse(GetTokenResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(IConversationPresenter.class.getSimpleName(),"网络异常 获取Token失败");
            }
        });
        RequestUtil.sendRequest(coversionView.getContext(), param, request);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CloseOrderResponse response) {
        if (response.getErrorCode() >= 0) {
            EventBus.getDefault().post(new CloseOrdEvent(response.getOrderId()));
            coversionView.closeOrderSuccess(response.getOrderId(), response.getExtend());
        } else {
            coversionView.closeOrderFailed(response.getErrorMsg());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RollBackResponse response) {
        if (response.getErrorCode() >= 0) {
            EventBus.getDefault().post(new RollBackOrdEvent(response.getOrderId()));
            coversionView.rollBackOrderSuccess(response.getOrderId());
        }else {
            coversionView.rollBackOrderFailed(response.getErrorMsg());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryCovOrderResponse response) {
        if (response.getErrorCode() >= 0) {
            if (null != response.getOrderInfoList() && response.getOrderInfoList().size() > 0) {
                coversionView.queryOrderSuccess(response.getOrderInfoList().get(0));
            } else {
                coversionView.queryOrderFailed(response.getErrorMsg());
            }
        } else {
            coversionView.queryOrderFailed(response.getErrorMsg());
        }
    }

    /**
     * 查询剩余时间接口回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryLeftTimeResponse response) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        queryLeftTimeRequest = null;
        if (response.getErrorCode() >= 0) {
            coversionView.queryLeftTimeSuccess(response);
        } else {
            coversionView.queryLeftTimeFailed(response.getErrorMsg());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryUserResponse response) {
        if (response.getErrorCode() >= 0) {
            coversionView.queryUserSuccess(response.getUser());
        } else {
            coversionView.queryUserFailed(response.getErrorMsg());
        }
    }

    /**
     * 健康卡扣卡接口回掉
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(PayControllerDocResponse response) {

        if (response.getErrorCode()>=0)
        {
            coversionView.payControllerDocSuccess(response);
        }else
        {
            coversionView.payControllerDocFailed(response.getErrorMsg());
        }

    }

    /**
     * 重新获取Token接口返回数据
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(GetTokenResponse response) {
        if (BuildConfig.LOG_DEBUG) {
            Log.e(ConversionPresenterCompl.class.getSimpleName(), "GetTokenResponse");
            if (!TextUtils.isEmpty(response.getToken()))
            {
                Log.e(ILoginPresenter.class.getSimpleName(), response.getToken());
            }
        }
        if (response.getErrorCode() >= 0) {

            if (coversionView.getApp().getUserModel().getUserId().equals(response.getUserId()))
            {
                coversionView.getApp().getUserModel().setRongToken(response.getToken());
                reConnect(response.getToken());
            }else
            {
                Log.e(IConversationPresenter.class.getSimpleName(),"获取Token失败:和本地当前用户不一致");
            }

        } else {
            Log.e(IConversationPresenter.class.getSimpleName(),"获取Token失败:"+response.getErrorMsg());
        }
    }


}
